<?php
/**
 * 超链接插件
 *
 * @author mmxie
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: DwzHref.php 1021 2011-11-09 01:06:33Z mmxie $
 */
class IG_Data_Plugin_DwzHref extends IG_Data_Plugin
{
    protected $_columns;

    public function setColumns(array $columns)
    {
        $this->_columns = $columns;
    }

    public function getColumns()
    {
        return $this->_columns;
    }

    public function after()
    {
        $source = $this->getSource();
        $params = $source->getParams();
        $rows   = &$source->getRows();
        $search = array();

        if (is_array(current($rows))) {
            foreach (array_keys(current($rows)) as $key) {
                $search[] = '{' . $key . '}';
            };
        }
        foreach (array_keys($params) as $key) {
            $search[] = '{' . $key . '}';
        }

        foreach ($rows as &$row) {
            foreach ($this->getColumns() as $index => $attrs) {
                if (!isset($row[$index])) continue;
                $attrs += array('target' => 'navTab');
                if (isset($attrs['href'])) {
                    $attrs['href'] = str_replace($search, $row + $params, $attrs['href']);
                }
                if (isset($attrs['title'])) {
                    $attrs['title'] = str_replace($search, $row + $params, $attrs['title']);
                }
                $row[$index] = '<a ' . $this->_htmlAttrs($attrs) . '>'
                             . $this->getView()->escape($row[$index])
                             . '</a>';
            }
        }
    }

    protected function _htmlAttrs($attrs)
    {
        $html = '';
        foreach ($attrs as $key => $attr) {
            $html .= "$key=\"$attr\" ";
        }
        return $html;
    }
}